#include "command_send.h"
#include <stdio.h>
#include "gus2_config.h"
#include "memserializer.h"
#include "gus_crc.h"
int write_data(u8 data);
void flush_port(void);
#define sendByte(byt) write_data((byt))
#define flushSendBuff() flush_port()
//void static sendByte(u8 byt)
//{
//    // printf("%02X ", byt);
//    write_data(byt);
//    
//}
//void static flushSendBuff()
//{
//    // printf("\n");
//    flush_port();
//}

void command_send(const bytearray_t* ba)
{
    // gusConfig
    u16 crcVal = CRC_INI_VAL;
    u8 byts[6];
    int count = 0;
    int i = 0;
    int len = ba->len + 2;
    count = memserializer(byts,"bbww", gusConfig.key1, gusConfig.key2, len, len);
    // send key and length
    for(i = 0; i < count; i++)
    {
        sendByte(byts[i]);
    }
    // send data
    for(i = 0; i < ba->len; i++)
    {
        sendByte(ba->data[i]);
        crc16byte(&crcVal, ba->data[i]);
    }
    // send crcval
    count = memserializer(byts, "w", crcVal);
    for(i = 0; i < count; i++)
    {
        sendByte(byts[i]);
    }
    flushSendBuff();
}
